/**
 * 搜索页面JavaScript
 */

// 搜索页面管理器
window.SearchPage = {
    // 当前页码
    currentPage: 1,

    // 是否正在加载
    isLoading: false,

    // 是否还有更多数据
    hasMore: true,

    // 当前搜索关键词
    keyword: '',

    // 当前排序方式
    currentSort: 'relevance',

    // 当前视图模式
    currentView: 'grid',

    // 货币符号
    currencySymbol: $('#currency-symbol').text(),

    // 初始化
    init(keyword, totalPages) {
        this.keyword = keyword;
        this.hasMore = totalPages > 1;
        this.bindEvents();
        this.initView();
        this.initInfiniteScroll();
    },

    // 绑定事件
    bindEvents() {
        // 绑定全局函数
        window.doSearch = () => this.doSearch();
        window.changeSort = () => this.changeSort();
        window.changeView = (view) => this.changeView(view);

        // 回车搜索
        $('#search-keyword').on('keypress', (e) => {
            if (e.key === 'Enter') {
                this.doSearch();
            }
        });

        // 排序变化
        $('#sort-select').on('change', () => {
            this.changeSort();
        });
    },

    // 初始化视图
    initView() {
        // 恢复视图偏好
        const savedView = localStorage.getItem('search_view') || 'grid';
        this.changeView(savedView);

        // 设置当前排序选项
        const urlParams = new URLSearchParams(window.location.search);
        const sortParam = urlParams.get('sort') || 'relevance';
        this.currentSort = sortParam;
        $('#sort-select').val(sortParam);

        // 聚焦搜索框（如果没有关键词）
        if (!this.keyword) {
            $('#search-keyword').focus();
        }
    },

    // 初始化无限滚动
    initInfiniteScroll() {
        if (!this.keyword || !this.hasMore) {
            return;
        }

        let scrollTimer = null;

        $(window).on('scroll', () => {
            if (scrollTimer) {
                clearTimeout(scrollTimer);
            }

            scrollTimer = setTimeout(() => {
                this.checkLoadMore();
            }, 100);
        });
    },

    // 检查是否需要加载更多
    checkLoadMore() {
        if (this.isLoading || !this.hasMore) {
            return;
        }

        const $window = $(window);
        const $document = $(document);
        const scrollTop = $window.scrollTop();
        const windowHeight = $window.height();
        const documentHeight = $document.height();

        // 距离底部300px时开始加载
        if (scrollTop + windowHeight >= documentHeight - 300) {
            this.loadMore();
        }
    },

    // 加载更多商品
    loadMore() {
        if (this.isLoading || !this.hasMore) {
            return;
        }

        this.isLoading = true;
        this.showLoadingIndicator();

        const nextPage = this.currentPage + 1;

        $.ajax({
            url: '/search',
            type: 'GET',
            data: {
                keyword: this.keyword,
                page: nextPage,
                sort: this.currentSort
            },
            dataType: 'json',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            },
            success: (response) => {
                if (response.code === 1) {
                    const data = response.data;

                    if (data.goods_list && data.goods_list.length > 0) {
                        this.appendGoods(data.goods_list);
                        this.currentPage = nextPage;

                        // 检查是否还有更多数据
                        if (data.goods_list.length < data.per_page || nextPage >= data.total_pages) {
                            this.hasMore = false;
                            this.showNoMoreIndicator();
                        }
                    } else {
                        this.hasMore = false;
                        this.showNoMoreIndicator();
                    }
                } else {
                    showError('加载失败: ' + (response.msg || '未知错误'), 3000);
                }
            },
            error: () => {
                showError('网络连接失败', 3000);
            },
            complete: () => {
                this.isLoading = false;
                this.hideLoadingIndicator();
            }
        });
    },

    // 追加商品到列表
    appendGoods(goodsList) {
        const container = document.getElementById('goods-container');
        const desktopContainer = container.querySelector('.hidden.md\\:grid');
        const mobileContainer = container.querySelector('.md\\:hidden');

        goodsList.forEach(goods => {
            // 为桌面端添加商品
            if (desktopContainer) {
                const desktopHtml = this.createDesktopGoodsItem(goods);
                desktopContainer.insertAdjacentHTML('beforeend', desktopHtml);
            }

            // 为移动端添加商品
            if (mobileContainer) {
                const mobileHtml = this.createMobileGoodsItem(goods);
                mobileContainer.insertAdjacentHTML('beforeend', mobileHtml);
            }
        });

    },

    // 创建桌面端商品项HTML
    createDesktopGoodsItem(goods) {
        const imageUrl = goods.slider_image && goods.slider_image[0]
            ? goods.slider_image[0]
            : '';

        // todo 符号单位待办
        const priceHtml = goods.price
            ? `<span class="theme-primary font-bold price-container flex gap-1 items-center">
                   <span class="text-xs currency-symbol">${this.currencySymbol}</span>
                   <span class="text-lg price-number">${goods.price}</span>
               </span>`
            : `<span class="theme-success font-bold text-lg">免费</span>`;

        return `
            <div class="cursor-pointer h-full" onclick="window.location.href='/item-${goods.id}'">
                <div class="theme-bg-primary rounded-lg overflow-hidden hover:theme-border-primary transition-colors h-full flex flex-col">
                    <!-- 商品图片 -->
                    <div class="relative aspect-w-2 aspect-h-1 theme-bg-muted overflow-hidden">
                        <img src="${imageUrl}"
                             alt="${goods.name}"
                             class="w-full h-32 object-cover lazy-image">
                    </div>

                    <!-- 商品信息 -->
                    <div class="p-3 flex-1 flex flex-col">
                        <div class="text-sm font-medium theme-text-primary line-clamp-2 h-10 leading-5 flex-1">
                            ${this.highlightKeyword(goods.name, this.keyword)}
                        </div>
                        <div class="flex items-center justify-between mt-2">
                            <div class="flex items-center">
                                ${priceHtml}
                            </div>
                            <div class="flex items-center space-x-1">
                                <span class="text-xs theme-text-muted">
                                    <i class="fas fa-eye mr-1"></i><span class="view-count" data-count="${goods.views}">${goods.views}</span>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    },

    // 创建移动端商品项HTML
    createMobileGoodsItem(goods) {
        const imageUrl = goods.slider_image && goods.slider_image[0]
            ? goods.slider_image[0]
            : '';

        // todo 符号单位待办

        const priceHtml = goods.price
            ? `<span class="theme-primary font-bold price-container flex gap-1 items-center">
                   <span class="text-xs currency-symbol">¥</span>
                   <span class="text-base price-number">${goods.price}</span>
               </span>`
            : `<span class="theme-success font-bold text-base">免费</span>`;

        return `
            <div class="cursor-pointer" onclick="window.location.href='/item-${goods.id}'">
                <div class="theme-bg-primary rounded-lg overflow-hidden hover:theme-border-primary transition-colors">
                    <div class="flex gap-3 p-3">
                        <!-- 商品图片 -->
                        <div class="flex-shrink-0 w-20 h-20 theme-bg-muted rounded overflow-hidden">
                            <img data-src="${imageUrl}"
                                 src=""
                                 alt="${goods.name}"
                                 class="w-full h-full object-cover lazy-image">
                        </div>

                        <!-- 商品信息 -->
                        <div class="flex-1 min-w-0 flex flex-col justify-between">
                            <div class="text-sm font-medium theme-text-primary mb-2 line-clamp-2 leading-tight">
                                ${this.highlightKeyword(goods.name, this.keyword)}
                            </div>
                            <div class="flex items-center justify-between">
                                <div class="flex items-center">
                                    ${priceHtml}
                                </div>
                                <div class="flex items-center space-x-1">
                                    <span class="text-xs theme-text-muted">
                                        <i class="fas fa-eye mr-1"></i><span class="view-count" data-count="${goods.views || 0}">${goods.views || 0}</span>
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    },

    // 执行搜索
    doSearch() {
        const keyword = $('#search-keyword').val().trim();
        if (keyword) {
            window.location.href = '/search-' + encodeURIComponent(keyword);
        }
    },

    // 改变排序
    changeSort() {
        const sortValue = $('#sort-select').val();
        const url = new URL(window.location);

        if (sortValue === 'relevance') {
            url.searchParams.delete('sort');
        } else {
            url.searchParams.set('sort', sortValue);
        }

        window.location.href = url.toString();
    },

    // 切换视图
    changeView(view) {
        this.currentView = view;
        const $container = $('#goods-container');
        const $gridBtn = $('#grid-view');
        const $listBtn = $('#list-view');

        if (view === 'grid') {
            $container.attr('class', 'goods-grid');
            $gridBtn.addClass('active theme-primary').removeClass('theme-text-secondary');
            $listBtn.removeClass('active theme-primary').addClass('theme-text-secondary');
        } else {
            $container.attr('class', 'space-y-4');
            $listBtn.addClass('active theme-primary').removeClass('theme-text-secondary');
            $gridBtn.removeClass('active theme-primary').addClass('theme-text-secondary');

            // 修改商品项样式为列表样式
            $container.find('.goods-item').attr('class', 'goods-item theme-bg-primary rounded-lg overflow-hidden shadow-sm hover:shadow-md transition-shadow cursor-pointer flex');
        }

        // 保存视图偏好
        localStorage.setItem('search_view', view);
    },

    // 高亮关键词
    highlightKeyword(text, keyword) {
        if (!keyword) return text;
        const regex = new RegExp(`(${keyword})`, 'gi');
        return text.replace(regex, '<mark class="bg-yellow-200">$1</mark>');
    },

    // 显示加载指示器
    showLoadingIndicator() {
        if (!$('#loading-indicator').length) {
            $('body').append(`
                <div id="loading-indicator" class="fixed bottom-4 left-1/2 transform -translate-x-1/2 bg-white rounded-lg shadow-lg px-4 py-2 flex items-center space-x-2 z-50">
                    <div class="loading"></div>
                    <span class="text-sm theme-text-secondary">加载更多...</span>
                </div>
            `);
        }
    },

    // 隐藏加载指示器
    hideLoadingIndicator() {
        $('#loading-indicator').remove();
    },

    // 显示没有更多数据指示器
    showNoMoreIndicator() {
        if (!$('#no-more-indicator').length) {
            $('#goods-container').after(`
                <div id="no-more-indicator" class="text-center py-8">
                    <p class="theme-text-muted">没有更多商品了</p>
                </div>
            `);
        }
    }
};
